

package com.zdkj.subway.stm.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.subway.stm.dto.in.SwBomSettleCycleCalculateDTO;
import com.zdkj.subway.stm.dto.in.SwBomSettleSubmitDTO;
import com.zdkj.subway.stm.dto.in.SwTvmSettleCycleCalculateDTO;
import com.zdkj.subway.stm.dto.in.SwTvmSettleSubmitDTO;
import com.zdkj.subway.stm.dto.out.SwPmLongPeriodSettlementDTO;
import com.zdkj.subway.stm.entity.SwStBomSettle;
import com.zdkj.subway.stm.entity.SwStIncomeSettle;
import com.zdkj.subway.stm.entity.SwStTvmSettle;
import com.zdkj.subway.stm.fegin.SupportService;
import com.zdkj.subway.stm.service.SwStBomSettleService;
import com.zdkj.subway.stm.util.DateUtilStm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;


/**
 * bom结算
 *
 * @author songtuo
 * @date 2020-08-09 17:14:32
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstbomsettle")
@Api(value = "swstbomsettle", tags = "bom结算管理")
@Slf4j
public class SwStBomSettleController {

    private final SwStBomSettleService swStBomSettleService;
    private final SupportService supportService;

    /**
     * 分页查询
     *
     * @param page          分页对象
     * @param swStBomSettle bom结算
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStBomSettlePage(Page page, SwStBomSettle swStBomSettle) {
        return R.ok(swStBomSettleService.page(page, Wrappers.query(swStBomSettle)));
    }


    /**
     * 通过id查询bom结算
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStBomSettleService.getById(id));
    }

//    /**
//     * 新增bom结算
//     * @param swStBomSettle bom结算
//     * @return R
//     */
//    @ApiOperation(value = "新增bom结算", notes = "新增bom结算")
//    @SysLog("新增bom结算" )
//    @PostMapping
//    @PreAuthorize("@pms.hasPermission('generator_swstbomsettle_add')" )
//    public R save(@RequestBody SwStBomSettle swStBomSettle) {
//        return R.ok(swStBomSettleService.save(swStBomSettle));
//    }
//
//    /**
//     * 修改bom结算
//     * @param swStBomSettle bom结算
//     * @return R
//     */
//    @ApiOperation(value = "修改bom结算", notes = "修改bom结算")
//    @SysLog("修改bom结算" )
//    @PutMapping
//    @PreAuthorize("@pms.hasPermission('generator_swstbomsettle_edit')" )
//    public R updateById(@RequestBody SwStBomSettle swStBomSettle) {
//        return R.ok(swStBomSettleService.updateById(swStBomSettle));
//    }

//    /**
//     * 通过id删除bom结算
//     * @param id id
//     * @return R
//     */
//    @ApiOperation(value = "通过id删除bom结算", notes = "通过id删除bom结算")
//    @SysLog("通过id删除bom结算" )
//    @DeleteMapping("/{id}" )
//    @PreAuthorize("@pms.hasPermission('generator_swstbomsettle_del')" )
//    public R removeById(@PathVariable Integer id) {
//        return R.ok(swStBomSettleService.removeById(id));
//    }

    /**
     * 新增tvm结算
     *
     * @return R
     */
    @ApiOperation(value = "Bom长周期结算", notes = "Bom长周期结算")
    @SysLog("Bom长周期结算")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('swstbomsettle_long_cycle_sellte')")
    public R longCycleSellte(@RequestBody SwBomSettleCycleCalculateDTO swBomSettleCycleCalculateDTO) {
        return R.ok(swStBomSettleService.longCycleSellt(swBomSettleCycleCalculateDTO));
    }

    /**
     * tvm收入结算数据 批量提交
     *
     * @param submitDTO
     * @return
     */
    @ApiOperation(value = "tvm收入结算数据 批量提交", notes = "tvm收入结算数据 批量提交")
    @PostMapping("/approval/status")
    @PreAuthorize("@pms.hasPermission('swstbomsettle_approval_status')")
    public R submit(@RequestBody SwBomSettleSubmitDTO submitDTO) {
        return R.ok(swStBomSettleService.submit(submitDTO));
    }

    /**
     * 导出bom数据
     */
    @ApiOperation(value = "导出Bom结算数据", notes = "导出Bom结算数据")
    @GetMapping("/export")
    public void export(Page page, SwStBomSettle swStBomSettle, HttpServletResponse response) {
        List<SwStBomSettle> records = swStBomSettleService.page(page, Wrappers.query(swStBomSettle)).getRecords();
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("Bom结算数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStBomSettle.class).
                    sheet("Bom结算数据").doWrite(records);
        } catch (IOException e) {
            log.error("导出Bom结算数据");
        }
    }

    /**
     * 定时任务调用，BOM结算，如果车站没有提交BOM结算，到设定的结算周期，系统自动按结算周期结算
     *
     * @return
     */
    @ApiOperation(value = "每天系统自动按设定结算周期结算", notes = "每天系统自动按设定结算周期结算")
    @Inner
    @PostMapping("/calc")
    public R calcBomSettle() {
        QueryWrapper<SwStBomSettle> wrapper = new QueryWrapper<SwStBomSettle>();
        wrapper.eq("isSubmit", 0);
        wrapper.eq("delFlag", 0);
        List<SwStBomSettle> swStBomSettleList = swStBomSettleService.list(wrapper);
        for (SwStBomSettle swStBomSettle : swStBomSettleList) {
            int day = DateUtilStm.getDayInterval(DateUtilStm.LocalDateToUdate(swStBomSettle.getSellStartTime()), new Date());
            SwPmLongPeriodSettlementDTO settlementDTOS = supportService.getLongPeriodSettlement(swStBomSettle.getStationCode(), swStBomSettle.getLineCode(), SecurityConstants.FROM_IN).getData();
            int setday=Integer.valueOf(settlementDTOS.getTvmSettlementTerm());
            if (day==setday) {
                swStBomSettle.setApprovalStatus("1");
                swStBomSettleService.save(swStBomSettle);
            }

        }
        return R.ok();
    }

}
